package com.atguigu.flink.chapter11;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.Schema;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/21 10:48
 */
public class Flink04_Table_File {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        // 直接从文件读取数据, 使用tableAPI
        Schema schema = new Schema()
            .field("id", DataTypes.STRING())
            .field("ts", DataTypes.BIGINT())
            .field("vc", DataTypes.INT());
    
        // 创建了一个临时的动态表, 与文件关联,
        tEnv
            .connect(new FileSystem().path("input/sensor.txt"))
            .withFormat(new Csv().fieldDelimiter(',').lineDelimiter("\n"))
            .withSchema(schema)
            .createTemporaryTable("sensor");// 临时表的表名
    
        Table sensor = tEnv.from("sensor");
    
        Table result = sensor
            .where($("id").isEqual("sensor_1"))
            .select($("id"), $("vc"), $("ts"));
        
        // 创建一个动态表与文件关联, 向动态表写数据, 会自动写入到文件中
        Schema schemaOut = new Schema()
            .field("id", DataTypes.STRING())
            .field("vc", DataTypes.INT())
            .field("ts", DataTypes.BIGINT());
        tEnv
            .connect(new FileSystem().path("input/out"))
            .withFormat(new Csv())
            .withSchema(schemaOut)
            .createTemporaryTable("out1");// 临时表的表名
        
        result.executeInsert("out1");  // 把result的结果插入到动态表out1中
    
    }
}
